<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="title">暴走电商 | 管理后台</h2>

      <el-tabs v-model="activeTab" stretch @tab-change="handleTabChange">
        <el-tab-pane label="账号登录" name="account"></el-tab-pane>
        <el-tab-pane label="手机登录" name="phone"></el-tab-pane>
      </el-tabs>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
      >
        <!-- 账号密码登录 -->
        <template v-if="activeTab === 'account'">
          <el-form-item prop="account">
            <el-input
              v-model="loginForm.account"
              placeholder="请输入账号"
              prefix-icon="User"
              size="large"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="rememberPassword">记住密码</el-checkbox>
          </el-form-item>
        </template>

        <!-- 手机验证码登录 -->
        <template v-else>
          <el-form-item prop="phone">
            <el-input
              v-model="loginForm.phone"
              placeholder="请输入手机号"
              prefix-icon="Iphone"
              size="large"
            />
          </el-form-item>

          <el-form-item prop="code">
            <div class="code-input">
              <el-input
                v-model="loginForm.code"
                placeholder="请输入验证码"
                prefix-icon="Message"
                size="large"
              />
              <el-button
                class="send-btn"
                :disabled="!canSendCode || countdown > 0"
                @click="sendCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : "获取验证码" }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="forget-password">
          <el-link type="info">忘记密码？</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import axios from "axios";
import AES from "@/utils/AES.js";

const activeTab = ref("account");
const loginFormRef = ref();
const countdown = ref(0);
// 从本地存储读取记住密码的状态，默认为false
const rememberPassword = ref(
  localStorage.getItem("rememberPassword") === "true"
);
let timer = null;

const router = useRouter();

const loginForm = reactive({
  account: "",
  password: "",
  phone: "",
  code: "",
});

// 手机号格式校验规则
const validatePhone = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/;
  if (!value) {
    callback(new Error("请输入手机号"));
  } else if (!reg.test(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};

const loginRules = reactive({
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 8, message: "账号长度不能少于8位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{6,}$/,
      message: "密码长度不小于6位,且必须包含字母和数字",
      trigger: "blur",
    },
  ],
  phone: [{ validator: validatePhone, trigger: "blur" }],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度必须为4位", trigger: "blur" },
  ],
});

// 是否可以发送验证码
const canSendCode = computed(() => {
  return /^1[3-9]\d{9}$/.test(loginForm.phone);
});

// 发送验证码
const sendCode = async () => {
  // let phoneData = {userPhone:loginForm.phone}
  try {
    const res = await axios.post("/api/auth/sendCode", {
      phone: loginForm.phone,
    });

    if (res.data.code === 200) {
      ElMessage.success("验证码发送成功");
      startCountdown();
    } else {
      ElMessage.error(res.data.msg || "发送失败");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("请求异常，请稍后重试");
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer);
      return;
    }
    countdown.value--;
  }, 1000);
};

// 切换登录方式时重置表单
const handleTabChange = () => {
  loginFormRef.value.resetFields();
};

// 登录处理
const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (!valid) return;

    ElMessage.success("登录提交中...");

    if (activeTab.value === "account") {
      // 账号密码登录
      const req = {
        userName: loginForm.account,
        pwd: AES.encrypt(loginForm.password),
      };
      axios.post("/api/auth/login", req).then((res) => {
        handleLoginResponse(res);
      });
    } else {
      // 手机验证码登录
      const req = {
        phone: loginForm.phone,
        code: loginForm.code,
      };
      axios.post("/api/auth/smsLogin", req).then((res) => {
        handleLoginResponse(res);
      });
    }
  });
};

onMounted(() => {
  // 只有在记住密码为true时才读取存储的账号密码
  if (rememberPassword.value) {
    const savedAccount = localStorage.getItem("savedAccount");
    const savedPassword = localStorage.getItem("savedPassword");
    if (savedAccount && savedPassword) {
      loginForm.account = savedAccount;
      loginForm.password = AES.decrypt(savedPassword);
    }
  } else {
    // 如果没有勾选记住密码，清除存储
    localStorage.removeItem("savedAccount");
    localStorage.removeItem("savedPassword");
  }
});

// 统一处理登录响应
const handleLoginResponse = (res) => {
  if (res.data.code === 200) {
    // 登录成功后
    const token = res.data.data.token;
    sessionStorage.setItem("token", token); // 持久化
    axios.defaults.headers.common.token = token; // 设置当前实例的默认头

    // 页面初始化时恢复token
    if (sessionStorage.getItem("token")) {
      axios.defaults.headers.common.token = sessionStorage.getItem("token");
    }
    ElMessage.success("登录成功");
    router.push("/main");
    // 这里可以添加跳转逻辑

    // 存储记住密码状态
    localStorage.setItem("rememberPassword", rememberPassword.value);

    // 只有勾选了记住密码才存储账号密码
    if (rememberPassword.value) {
      localStorage.setItem("savedAccount", loginForm.account);
      localStorage.setItem("savedPassword", AES.encrypt(loginForm.password));
    } else {
      localStorage.removeItem("savedAccount");
      localStorage.removeItem("savedPassword");
    }
  } else {
    ElMessage.error(res.data.msg || "登录失败");
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.login-form {
  .el-form-item {
    margin-bottom: 24px;
  }
}

.code-input {
  display: flex;
  gap: 10px;

  .send-btn {
    width: 120px;
    flex-shrink: 0;
  }
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.forget-password {
  text-align: right;
  margin-top: -10px;

  .el-link {
    font-size: 14px;
  }
}

.el-tabs {
  margin-bottom: 20px;
}
</style>
